package com.wsy.wsyojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import com.wsy.wsyojcodesandbox.model.ExecuteCodeRequest;
import com.wsy.wsyojcodesandbox.model.ExecuteCodeResponse;
import com.wsy.wsyojcodesandbox.model.ExecuteMessage;
import com.wsy.wsyojcodesandbox.model.JudgeInfo;
import com.wsy.wsyojcodesandbox.security.DefaultSecurityManager;
import com.wsy.wsyojcodesandbox.security.DenySecurityManager;
import com.wsy.wsyojcodesandbox.utils.ProcessUtils;
import com.wsy.wsyojcodesandbox.utils.Trie;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Deprecated
public class JavaNativeCodeSandbox implements CodeSandBox {

    //默认存放文件夹名
    private static final String GLOBAL_CODE_DIR = "tempCode";

    //默认类名
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    //最大运行时间
    private static final long TIME_OUT = 5000L;

    //自定义安全管理器路径
    private static final String SECURITY_MANAGER_PATH =
            "E:\\JavaCodeSandbox\\src\\main\\resources\\security\\MySecurityManager.java";

    //自定义安全管理器类名
    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";

    //敏感词黑名单，但是无法顾及所有，以及各语言类名方法名有所不同
    private static final List<String> blackList = Arrays.asList("Files", "exec");

    //建前缀树
    private static final Trie TRIE;

    //静态代码块初始化
    static {
        TRIE = new Trie(blackList);
    }

    public static void main(String[] args) {
        JavaNativeCodeSandbox javaNativeCodeSandbox = new JavaNativeCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
        //正常
//        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);

        //异常问题
        String code = ResourceUtil.readStr("testCode/unSafeCode/ReadFileErr.java", StandardCharsets.UTF_8);

        //Scanner输入
//        String code = ResourceUtil.readStr("testCode/simpleCompute/Main.java", StandardCharsets.UTF_8);

        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");

        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }

    /**
     * 从提交的请求体中读代码，存放到本地文件，进行编译
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        //用java的安全管理器进行权限控制, 但是得加白名单
//        System.setSecurityManager(new DefaultSecurityManager());

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        //检查是否包含敏感词
//        WordTree wordTree = new WordTree();
        String found = TRIE.containsBlacklistWord(code);
        if(found != null) {
            System.out.println("找到了:" + found);
            return getResp(new RuntimeException("敏感词检测..."));
        }

        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR;
        //判断全局代码目录是否存在，没有就新建
        if(!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        //1. 用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2. 编译代码得到.class
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcess(compileProcess, "compile");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return getResp(e);
        }

        //3. 执行代码得到结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            //-Xmx256m 控制jvm内存最多256M，控制OOM
            String runCmd = String.format("java -Xmx512m -Dfile.encoding=UTF-8 -cp %s Main %s",
                    userCodeParentPath, inputArgs);

            try {
                //该处已经开启一个新子进程，runProcess
                Process runProcess = Runtime.getRuntime().exec(runCmd);

                //新建线程观察该沙箱运行进程，控制超时
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时中断...");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).start();

                ExecuteMessage executeMessage = ProcessUtils.runProcess(runProcess, "execute");
//                ExecuteMessage executeMessage =
//                        ProcessUtils.runInteractProcess(runProcess, inputArgs);
                executeMessageList.add(executeMessage);
                System.out.println(executeMessage);
            } catch (Exception e) {
                e.printStackTrace();
                return getResp(e);
            }
        }

        //4. 整理输出
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //取最大运行时间？
        //可以改造成获取每一个测试用例的运行时间
        long maxTime = 0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();

            if(StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long runtime = executeMessage.getTime();
            if(runtime != null) {
                maxTime = Math.max(maxTime, runtime);
            }
        }
        if(outputList.size() == executeMessageList.size()) {
            //每条都正常输出，没有编译的问题
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);

        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        //怎么获取运行内存？
//        judgeInfo.setMemory();
        executeCodeResponse.setJudgeInfo(judgeInfo);

        //5. 清理文件
        if(userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }

        return executeCodeResponse;
    }

    //6. 错误处理: 定义一个新的方法，返回沙箱出错信息。
    //返回沙箱出错时的信息
    private ExecuteCodeResponse getResp(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
